#pragma once

#include <iostream>
#include <vector>
#include <cassert>
#include "util.hpp"

namespace bitlog
{
    #define DEFAULT_BUFFER_SIZE (1024*1024*100)
    class Buffer
    {
        private:
            std::vector<char> _buffer;
            size_t _reader_idx;
            size_t _writer_idx;

        public:
            Buffer() : _buffer(DEFAULT_BUFFER_SIZE), _reader_idx(0), _writer_idx(0) { }

            // 向缓冲区写入数据
            void push(const char *data, size_t len)
            {
                if(len > writeAbleSize())
                {
                    return;
                }

                std::copy(data, data + len, &_buffer[_writer_idx]);
                moveWriter(len);
            }

            // 返回可读数据的起始位置
            const char* begin()
            {
                return &_buffer[_reader_idx];
            }

            // 返回可读写数据的长度
            size_t readAbleSize()
            {
                return _writer_idx - _reader_idx;
            }
            size_t writeAbleSize()
            {
                return _buffer.size() - _writer_idx;
            }


            // 重置读写位置，初始化缓冲区
            void reset()
            {
                _reader_idx = 0;
                _writer_idx = 0;
            }

            // 对buffer实现交换操作
            void swap(Buffer &buffer)
            {
                _buffer.swap(buffer._buffer);
                std::swap(_reader_idx, buffer._reader_idx);
                std::swap(_writer_idx, buffer._writer_idx);
            }

            // 判断缓冲区是否为空
            bool empty()
            {
                return _reader_idx == _writer_idx;
            }
        
        private:
            // 对读写指针向后偏移
            void moveWriter(size_t len)
            {
                assert(len <= writeAbleSize());
                _writer_idx += len;
            }
            void moveReader(size_t len)
            {
                assert(len <= readAbleSize());
                _reader_idx += len;
            }
    };
}